package jtt809;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import jtt809.handler.initializer.SlaveJtt809Initializer;

/**
 * 从链路
 * 下级平台服务端
 */
public class SlaveLinkClientManager implements Runnable{

    /**
     * 日志类
     */
    private static final Log logger = LogFactory.get();

    /**
     * 绑定IP
     */
    private String ip;

    /**
     * 绑定端口
     */
    private int port;

    public SlaveLinkClientManager(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public void run() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    // 保持长连接
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    // 标识当服务器请求处理线程全满时，用于临时存放已完成三次握手的请求的队列的最大长度
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new SlaveJtt809Initializer());

            // 绑定端口，同步等待成功
            ChannelFuture channelFuture = serverBootstrap.bind(this.ip, this.port).sync();
            logger.info("==========> 下级平台服务端启动成功。绑定IP：{}，绑定端口：{}", this.ip, this.port);

            // 等待服务器监听端口关闭
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            logger.info("==========> 下级平台服务端启动出错。错误：{}", e.getMessage());
            e.printStackTrace();
        } finally {
            // 释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
